// pages/hxnBuyLimit/index.js
//更多限时抢购
let url_js = require("../../utils/url.js");
let common_js = require("../../utils/common.js");
let user_js = require("../../utils/user.js");
let sys_js = require("../../utils/system.js");
let cart_js = require("../../utils/cart.js");
let ubt_js = require("../../utils/ubt.js");
let name_js = require("../../utils/ubtButtonName.js");
let api = require("../../utils/apiRequest.js");
let page_js = require("../../utils/pageOptions.js");
let wxp = require("../../utils/wxp.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    pages: 1, //页面数
    buyingInfo: null,
    userInfo: null,
    pageScrollTop: 0,
    containerTouchmove: '',
    barInfo: {},
    tabList: [],
    tabIndex: 0,
    contentGoodsList: [], //所有的内容列表
    segTaped: false,
    topHeightInfo: null, //放有背景图的选择
    anchorArray: [], //锚点数组
    bgImgUrl: url_js.imgUrl + "buy_limt_bg.png",
    goodsPropertyInfo: {
      pageShow: false, //页面展示
      dismiss: false, //手动设置隐藏，当属性页面隐藏完成后，pageShow设置false
    },
    addCartSelctedGoodsInfo: null, //当前添加购物车的商品，只有当有多种规格时有数据
    shareInfo: null, //分享信息
    notificationIdList: [], //订阅消息
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //业务埋点
    ubt_js.myPageView(common_js.currentPageName(), options);
    //1.禁止转发
    wx.hideShareMenu();
    //2.初始化数据
    this.initData(options);
  },

  // 初始化数据
  initData(options) {
    if (!user_js.hasRole()) {
      //1.save param
      let obj = {
        url: '../hxnBuyLimit/index',
        param: ''
      }
      page_js.savePageOptionsInfo(obj);
      //2.relauch
      //*********跳转放在onshow
      return;
    } else {
      //有角色，展示页面
      this.initUnShareOptionsData(options);
      //获取远程仓库数据
      this.getRemoteDatas(true);
    }
  },

  //初始化options数据
  initUnShareOptionsData: function (options) {
    //userInfo
    let tempUserInfo = user_js.userInfo();
    let sysInfo = sys_js.navInfo();
    this.setData({
      userInfo: tempUserInfo,
      pages: getCurrentPages(),
      barInfo: {
        statusBarHeight: sysInfo.statusBarHeight,
        navBarHeight: sysInfo.navBarHeight
      }
    });
  },

  // 获取数据
  getRemoteDatas: function (withShareInfo) {
    let requestList = [];
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: this.data.userInfo.code,
      shopId: this.data.userInfo.ztd.id
    }
    requestList.push(api.wxRequest(url_js.listUrl, data));
    // 限时抢购通知
    requestList.push(api.wxRequest(url_js.notificationIdUrl));

    if (withShareInfo) {
      let shareData = {
        cityId: this.data.userInfo.ztd.cityId,
        code: this.data.userInfo.code,
        shopId: this.data.userInfo.ztd.id,
        type: 1
      };
      requestList.push(api.wxRequest(url_js.homeShareConfigUrl, shareData));
    }
    //获取数据
    Promise.all(requestList).then(results => {
      this.handleListData(results[0]);
      this.handleNotificationIdData(results[1]);
      if (withShareInfo) {
        this.handleHomeShareConfigData(results[2]);
      }
    }).catch(err => {
      common_js.log(err);
    });
  },


  //处理返回的tab数据
  handleListData: function (res) {
    //分享过来，如果当前点位不售卖分享过来的商品，回首页
    if (res.code == 704) {
      wx.switchTab({
        url: '../index/index'
      });
      return;
    }

    //设置数据
    if (res.result.length > 0) {
      let tmpList = res.result;
      // 内容列表
      let contentList = [];
      tmpList.forEach((ele) => {
        let listItem = {
          item: ele,
          list: []
        }
        contentList.push(listItem);
      });
      this.setData({
        tabList: tmpList,
        contentGoodsList: contentList,
        buyingInfo: {
          remark: res.remark,
          userImgs: res.userImgs
        }
      });

      // 获取所有的子项产品
      this.getAllTabGoods();
    }
  },

  // 处理秒杀提醒id
  handleNotificationIdData(res) {
    this.setData({
      notificationIdList: res.result
    })
  },

  // 获取所有的子项产品
  getAllTabGoods() {
    let requestList = [];
    this.data.tabList.forEach((ele) => {
      let data = {
        cityId: this.data.userInfo.ztd.cityId,
        code: user_js.getCode(),
        flashSaleId: ele.id,
        shopId: this.data.userInfo.ztd.id
      }
      requestList.push(api.wxRequest(url_js.listProductUrl, data));
    });

    Promise.all(requestList).then(results => {
      let tmpList = this.data.contentGoodsList;
      results.forEach((ele, index) => {
        let contentItem = tmpList[index];
        contentItem.list = ele.result;
      });
      this.setData({
        contentGoodsList: tmpList
      }, res => {
        this.queryAnchorAHeight();
      });
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理返回的分享数据
  handleHomeShareConfigData: function (res) {
    this.setData({
      shareInfo: res.result
    });
    //1.开启转发
    wx.showShareMenu({});
  },

  // 返回
  onNavBack() {
    wx.navigateBack({
      delta: 1,
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //如果是分享进来的，并且没有选择角色，进入角色选择页面
    if (page_js.pageOptionsInfo()) {
      //2.relauch
      wx.reLaunch({
        url: '../indexSearchShop/indexSearchShop'
      });
    }
  },


  //添加商品
  onAddGoods: function (e) {
    if (!user_js.isLogin()) {
      wx.navigateTo({
        url: '../loginIndex/loginIndex'
      });
      return
    }
    let index = e.currentTarget.dataset.index;
    let firstIndex = e.currentTarget.dataset.firstindex;
    let item = this.data.contentGoodsList[firstIndex].list[index];
    if (item.skuList && item.skuList.length > 1) {
      if (item.dimensions.length == 0) {
        common_js.showToast("商品多规格属性不存在！");
        return;
      }
      //多规格,选择规格加入购物车
      //展示多规格商品
      let tmpGoodsPropertyInfo = this.data.goodsPropertyInfo;
      tmpGoodsPropertyInfo.pageShow = true;
      this.setData({
        addCartSelctedGoodsInfo: item,
        goodsPropertyInfo: tmpGoodsPropertyInfo,
        containerTouchmove: 'preventTouchMove'
      });
    } else {
      //单一规格,直接添加购物车
      if (item.skuList == 0) {
        common_js.showToast("商品sku不存在");
        return;
      }
      //限时抢购单独判断
      if (item.type != 0) {
        let skuItem = item.skuList[0];
        let cartLimitCount = cart_js.limitSkuCountWithSkuId(skuItem.id);
        let isAlert = (cartLimitCount == 0) ? (item.count > skuItem.userBuyLimit) : (cartLimitCount >= skuItem.userBuyLimit);
        if (isAlert) {
          common_js.showModal("每人限购" + skuItem.userBuyLimit + "件，超过的件数将以原价支付！", null, true, null, "我知道了", () => {
            this.requestToAddCart(item.skuList[0], item.id, item.skuList[0].id, 1);
          })
          return;
        }
      }
      this.requestToAddCart(item.skuList[0], item.id, item.skuList[0].id, 1);
    }
    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.buyLimitGoodsAdd);
  },

  //增加购物车
  requestToAddCart: function (skuItem, productId, skuId, num) {
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      num: num,
      productId: productId,
      shopId: this.data.userInfo.ztd.id,
      skuId: skuId
    };
    api.wxRequest(url_js.cartAddUrl, data).then(res => {
      this.handleAddCartData(res, skuItem, skuId, num);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理添加购物车
  handleAddCartData: function (res, skuItem, skuId, num) {
    cart_js.addCart(skuItem, skuId, num);
    common_js.showToast("添加购物车成功");
  },

  //商品详情
  onGoodsDetail: function (e) {
    let index = e.currentTarget.dataset.index;
    let firstIndex = e.currentTarget.dataset.firstindex;
    let item = this.data.contentGoodsList[firstIndex].list[index];
    wx.navigateTo({
      url: '../goodsDetails/goodsDetails?productId=' + item.id
    })
  },

  //隐藏商品属性页面
  onHidePropertyPageView: function (e) {
    let tmpGoodsPropertyInfo = this.data.goodsPropertyInfo;
    tmpGoodsPropertyInfo.dismiss = true;
    this.setData({
      goodsPropertyInfo: tmpGoodsPropertyInfo
    });
  },

  //商品属性选择确定
  onGoodsPropertyEnsure: function (e) {
    //消失
    this.onGoodsPropertyHidden();
    //添加购物车
    if (e) {
      let item = e.detail;
      //限时抢购单独判断
      if (this.data.addCartSelctedGoodsInfo.type != 0) {
        let skuItem = item.sku;
        let cartLimitCount = cart_js.limitSkuCountWithSkuId(skuItem.id);
        let isAlert = (cartLimitCount == 0) ? (item.count > skuItem.userBuyLimit) : (cartLimitCount >= skuItem.userBuyLimit);
        if (isAlert) {
          common_js.showModal("每人限购" + skuItem.userBuyLimit + "件，超过的件数将以原价支付！", null, true, null, "我知道了", () => {
            this.requestToAddCart(item.sku, this.data.addCartSelctedGoodsInfo.id, item.sku.id, item.count);
          })
          return;
        }
      }
      this.requestToAddCart(item.sku, this.data.addCartSelctedGoodsInfo.id, item.sku.id, item.count);
    }
  },

  //商品属性选择
  onGoodsPropertyHidden: function (e) {
    let tmpGoodsPropertyInfo = this.data.goodsPropertyInfo;
    tmpGoodsPropertyInfo.pageShow = false;
    tmpGoodsPropertyInfo.dismiss = false,
      this.setData({
        containerTouchmove: '',
        goodsPropertyInfo: tmpGoodsPropertyInfo
      });
  },

  //隐藏商品属性页面
  onHidePropertyPageView: function (e) {
    let tmpGoodsPropertyInfo = this.data.goodsPropertyInfo;
    tmpGoodsPropertyInfo.dismiss = true;
    this.setData({
      goodsPropertyInfo: tmpGoodsPropertyInfo
    });
  },

  // 监听用户滑动页面事件
  onPageScroll: function (e) {
    let topY = e.scrollTop + "px";
    this.setData({
      pageScrollTop: topY
    });
  },

  //顶部切换
  onseg: function (e) {
    let index = e.currentTarget.dataset.index;
    if (this.data.tabIndex == index) return;
    this.segSyncClicked(index);
  },

  // seg点击了
  segSyncClicked(index) {
    // set data
    this.setData({
      segTaped: true
    });
    this.setData({
      tabIndex: index,
    }, res => {
      let timeId = setTimeout(() => {
        clearTimeout(timeId);
        this.setData({
          segTaped: false
        });
      }, 200);
    });
  },

  handelScroll(e) {
    let scrollTop = e.detail.scrollTop;
    if (scrollTop < 0) return;
    // 找不到的情况就是最后一个
    let found = this.data.anchorArray.findIndex(e => e > scrollTop);
    if (found != -1) {
      if (this.data.tabIndex == found - 1) return;
      this.setData({
        tabIndex: found - 1
      });
    } else {
      if (this.data.tabIndex == this.data.anchorArray.length - 1) return;
      this.setData({
        tabIndex: (this.data.anchorArray.length - 1)
      });
    }
  },

  //计算高度
  queryAnchorAHeight() {
    let query = wx.createSelectorQuery().in(this);
    let heightArr = [];
    query.select('.top-c').boundingClientRect();
    query.selectAll('.v-out-item').boundingClientRect();
    query.exec(res => {
      let topHeightInfo = res[0];
      res[1].forEach((res) => {
        heightArr.push(res.top - topHeightInfo.bottom);
      })
      this.setData({
        topHeightInfo: topHeightInfo,
        anchorArray: heightArr
      });
    });
  },

  // 获取通知的id
  getSubscribeMessagetmplIds() {
    return this.data.notificationIdList;
  },

  // 秒杀提醒
  // 检查模板消息发送情况
  subscribeMessageSuccessStatusList(res) {
    return this.data.notificationIdList.filter(item => {
      return res[item.id] == 'accept';
    });
  },

  // 订阅消息弹框
  onAlert() {
    let ids = this.getSubscribeMessagetmplIds();
    wxp.requestSubscribeMessage({
      tmplIds: ids
    }).then(res => {
      let list = this.subscribeMessageSuccessStatusList(res);
      if (list.length != 0 && (list.length != this.data.notificationIdList.length)) {
        this.goSettingUI('亲，我们未获得您的全部订阅消息推送权限，是否打开设置?');
      } else {
        // 订阅成功
      }
    }).catch(err => {
      if (err.errCode == 20004) {
        //打开设置
        this.goSettingUI('亲，我们未获得您的订阅消息推送权限，是否打开设置?');
      } else {
        // 订阅失败
        common_js.showToast(err.errMsg);
      }
    });
  },

  // 提示是否打开消息推送设置页面
  goSettingUI(content) {
    wxp.showModal({
      content: content
    }).then(res => {
      // 打开设置
      return wxp.openSetting({
        withSubscriptions: true
      });
    }).then(res => {
      // 打开设置，并返回
      common_js.log(res);
    }).catch(err => {
      common_js.log(err);
    });
  },


  // 去首页
  onHome() {
    wx.switchTab({
      url: '/pages/index/index',
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.buyLimitShare);

    return this.shareAppMessage();
  },
  //获取分享的AppMessage
  shareAppMessage: function () {
    let tmpPath = '/pages/hxnBuyLimit/index';
    return {
      title: this.data.shareInfo ? this.data.shareInfo.title : '好想你心选',
      path: tmpPath,
      imageUrl: this.data.shareInfo ? this.data.shareInfo.href : ''
    }
  },
})